package com.example.study

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.window.embedding.ActivityFilter
import androidx.window.embedding.EmbeddingAspectRatio
import androidx.window.embedding.RuleController
import androidx.window.embedding.SplitAttributes
import androidx.window.embedding.SplitPairFilter
import androidx.window.embedding.SplitPairRule
import androidx.window.embedding.SplitPlaceholderRule
import androidx.window.embedding.SplitRule

/**
 * Created by lijinxi on 2024/3/2
 * @Description:
 */
class SplitManager {
    companion object {
        fun create(context: Context) {
            val splitPairFilter = SplitPairFilter(
                ComponentName(context, ListActivity::class.java),
                ComponentName(context, DetailActivity::class.java),
                null
            )
            val filterSet = setOf(splitPairFilter)
            val splitAttributes = SplitAttributes.Builder().apply {
                setSplitType(SplitAttributes.SplitType.ratio(0.33f))
                setLayoutDirection(SplitAttributes.LayoutDirection.LEFT_TO_RIGHT)
            }.build()
            val splitPairRule = SplitPairRule.Builder(filterSet).apply {
                setDefaultSplitAttributes(splitAttributes)
                setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ratio(1.2f))
                setMinWidthDp(480)
                setMinSmallestWidthDp(420)
                setFinishPrimaryWithSecondary(SplitRule.FinishBehavior.NEVER)
                setFinishSecondaryWithPrimary(SplitRule.FinishBehavior.ALWAYS)
                setClearTop(false)
            }.build()
            val ruleController = RuleController.getInstance(context)
            ruleController.addRule(splitPairRule)

            val placeholderActivityFilter = ActivityFilter(
                ComponentName(context, ListActivity::class.java),
                null
            )
            val placeholderActivityFilterSet = setOf(placeholderActivityFilter)
            val splitPlaceholderRule = SplitPlaceholderRule.Builder(
                placeholderActivityFilterSet,
                Intent(context, PlaceholderActivity::class.java)
            ).apply {
                setDefaultSplitAttributes(splitAttributes)
                setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ratio(1.2f))
                setMinWidthDp(480)
                setMinSmallestWidthDp(420)
                setFinishPrimaryWithPlaceholder(SplitRule.FinishBehavior.ALWAYS)
            }.build()
            ruleController.addRule(splitPlaceholderRule)
        }
    }
}